package com.example.Controller;
import com.example.entity.PageResult;
import com.example.entity.vo.UsersVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Controller基类
 * 提供分页处理和当前用户获取功能
 */
@RestController
public abstract class BaseController {

//    获取当前 HTTP 请求对象
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
//    获取当前会话对象
    protected HttpSession getSession() {
        return getRequest().getSession();
    }

//    从会话中获取登录用户名
    protected String getLoginUsername() {
        return (String) getSession().getAttribute("username");
    }
    // post传参 获取参数
    protected void startPageByPost(@RequestBody UsersVo params) {
        Integer pageNum =  params.getPageNum();
        Integer pageSize = params.getPageSize();

        // 默认值处理
        if (pageNum == null || pageNum <= 0) pageNum = 1;
        if (pageSize == null || pageSize <= 0) pageSize = 10;

        PageHelper.startPage(pageNum, pageSize);
    }
    // GET请求时 进行分页的处理 从请求参数中获取分页信息
    protected void startPageByGet() {
        HttpServletRequest request = getRequest();
        Integer pageNum = Integer.valueOf(request.getParameter("pageNum"));
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));

        // 默认值处理
        if (pageNum == null || pageNum <= 0) pageNum = 1;
        if (pageSize == null || pageSize <= 0) pageSize = 10;

        PageHelper.startPage(pageNum, pageSize);
    }
   // 封装分页的结果
    protected <T> PageResult<T> getDataTable(List<T> list) {
        PageInfo<T> pageInfo = new PageInfo<>(list);
        PageResult<T> result = new PageResult<>();
        result.setCode(200);
        result.setRows(list);
        result.setTotal(pageInfo.getTotal());
        return result;
    }
}
